use tide::{Request, Response, StatusCode, Body,};

use crate::state::State;

pub mod out;
mod worker;
mod table;

pub async fn sealing_jobs(req: Request<State>) -> tide::Result<impl Into<Response>>{
    let key = req.param("key")?;
    let state = req.state();
    let sealer = state.node(key);
    let ret = if let Some(n) = sealer {
        worker::worker_sealing_jobs(&state.database(), state.client(), &n, key).await
    } else {
        Err(anyhow::anyhow!("node for {} not found.", key))
    };
    match ret {
        Err(e) => {
            log::error!("query data error: {:?}", e);
            Err(tide::Error::from_str(StatusCode::InternalServerError, e.to_string()))
        },
        Ok(r) => {
            Ok(Response::builder(StatusCode::Ok)
                .body(Body::from_json(&r)?)
                .build())
        }
    }
}